package com.sephiron.clocksynchronizer;

import java.util.Calendar;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.NumberPicker;
import android.widget.NumberPicker.OnValueChangeListener;
import android.widget.TimePicker;
import android.widget.TimePicker.OnTimeChangedListener;

public class TimePickerFragment extends DialogFragment {
	public static final String EXTRA_TIME = "com.sephiron.clocksynchronizer.time";
	public static final String TAG = "TimePickerFragment";
	private Calendar mPickerTime;

	private TimePicker timePicker;
	private NumberPicker secondPicker;
	private EditText secondTextField;

	public static TimePickerFragment newInstance(Calendar time) {
		Bundle args = new Bundle();
		args.putSerializable(EXTRA_TIME, time);

		TimePickerFragment fragment = new TimePickerFragment();
		fragment.setArguments(args);

		return fragment;
	}

	private void sendResult(int resultCode) {
		if (getTargetFragment() == null) {
			return;
		}

		Intent i = new Intent();
		i.putExtra(EXTRA_TIME, mPickerTime);
		getTargetFragment().onActivityResult(getTargetRequestCode(),
				resultCode, i);
	}

	@Override
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	public Dialog onCreateDialog(Bundle savedInstanceState) {
		mPickerTime = (Calendar) ((Calendar) getArguments().getSerializable(EXTRA_TIME)).clone();
//		Toast.makeText(getActivity(), String.valueOf(mPickerTime.get(Calendar.MINUTE)), Toast.LENGTH_SHORT).show();
		View v = getActivity().getLayoutInflater().inflate(
				R.layout.dialog_time, null);

		timePicker = (TimePicker) v.findViewById(R.id.dialog_time_timePicker);
		timePicker.setIs24HourView(true);

		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
			secondTextField = (EditText) v.findViewById(R.id.dialog_time_secTV);
			secondTextField.addTextChangedListener(new TextWatcher() {
				@Override
				public void onTextChanged(CharSequence c, int start,
						int before, int count) {
					if (c.length() != 0) {
						mPickerTime.set(Calendar.SECOND,
								Integer.parseInt(c.toString()));
					}
				}

				public void beforeTextChanged(CharSequence c, int start,
						int count, int after) {
					// this space intentionally left blank
				}

				public void afterTextChanged(Editable c) {
					// this one too
				}
			});

			secondTextField
					.setFilters(new InputFilter[] { new InputFilterMinMax("0",
							"59") });

			Button plus1sec = (Button) v
					.findViewById(R.id.dialog_time_plus1sec);
			plus1sec.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					int t = Integer.parseInt(secondTextField.getText()
							.toString());
					if (t == 59) {
						secondTextField.setText("0");
					} else {
						secondTextField.setText(String.valueOf(++t));
					}

				}
			});

			Button minus1sec = (Button) v
					.findViewById(R.id.dialog_time_minus1sec);
			minus1sec.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					int t = Integer.parseInt(secondTextField.getText()
							.toString());
					if (t == 0) {
						secondTextField.setText("59");
					} else {
						secondTextField.setText(String.valueOf(--t));
					}
				}
			});

		} else {
			secondPicker = (NumberPicker) v.findViewById(R.id.dialog_time_secondPicker);
			secondPicker.setMaxValue(59);
			secondPicker.setMinValue(0);
			secondPicker.setOnValueChangedListener(new OnValueChangeListener() {

				@Override
				public void onValueChange(NumberPicker picker, int oldVal,
						int newVal) {
					mPickerTime.set(Calendar.SECOND, newVal);
//					Toast.makeText(getActivity(), "onvalchange" + String.valueOf(mPickerTime.get(Calendar.MINUTE)), Toast.LENGTH_SHORT).show();
					getArguments().putSerializable(EXTRA_TIME, mPickerTime);
				}
			});
		}

		updateDialog();
		
		timePicker.setOnTimeChangedListener(new OnTimeChangedListener() {

			@Override
			public void onTimeChanged(TimePicker view, int hour, int minute) {
				
				mPickerTime.set(Calendar.HOUR_OF_DAY, hour);
//				Toast.makeText(getActivity(), "ontimechange1 " + String.valueOf(mPickerTime.get(Calendar.MINUTE)), Toast.LENGTH_SHORT).show();
				mPickerTime.set(Calendar.MINUTE, minute);
//				Toast.makeText(getActivity(), "ontimechange2 " + String.valueOf(mPickerTime.get(Calendar.MINUTE)), Toast.LENGTH_SHORT).show();
				getArguments().putSerializable(EXTRA_TIME, mPickerTime);
				Log.d(TAG, "onTimeChanged Called");
				Exception ex = new Exception();
				ex.printStackTrace();
			}
		});

		return new AlertDialog.Builder(getActivity())
				.setView(v)
				.setTitle(R.string.time_picker_title)
				.setNegativeButton(android.R.string.cancel,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub

							}
						})
				.setPositiveButton(android.R.string.ok,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								sendResult(Activity.RESULT_OK);
							}
						}).create();
	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	protected void updateDialog() {
		timePicker.setCurrentHour(mPickerTime.get(Calendar.HOUR_OF_DAY));
		Log.i(TAG, "updateDialog called(hour)");
		timePicker.setCurrentMinute(mPickerTime.get(Calendar.MINUTE));
		Log.i(TAG, "updateDialog called(hour)");
		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
			secondTextField.setText(String.valueOf(mPickerTime
					.get(Calendar.SECOND)));
		} else {
			secondPicker.setValue(mPickerTime.get(Calendar.SECOND));
		}
	}
}